package sealte.hvpms.servlet.vp;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sealte.hvpms.dao.PollDAO;
import sealte.hvpms.dao.PollOptionDAO;
import sealte.hvpms.dao.impl.PollDAOImpl;
import sealte.hvpms.dao.impl.PollOptionDAOImpl;
import sealte.hvpms.pojo.Poll;
import sealte.hvpms.pojo.PollOption;
import sealte.hvpms.pojo.UserCreate;
import sealte.hvpms.util.HVPMSTools;

public class BatchExportVPs extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssZ");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setHeader("Cache-Control","no-cache");
		response.reset();
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename="+sdf.format(new Date())+".xls");
		UserCreate uc = (UserCreate)request.getSession().getAttribute("UserCreate");
		if(uc!=null){
			String polls = request.getParameter("polls");
			if(polls!=null&&!polls.equals("")){
				String[] poll_idStrs = polls.split("[,]");
				Map<Integer,Poll> map1 = new HashMap<Integer,Poll>();
				Map<Integer,List<PollOption>> map2 = new HashMap<Integer,List<PollOption>>();
				Poll poll = null;
				PollDAO pb = null;
				PollOptionDAO pob = null;
				List<PollOption> all = null;
				String[] tableHead = new String[5];
				tableHead[0] = "投票标题：";
				tableHead[1] = "总票数：";
				tableHead[2] = "序号";
				tableHead[3] = "选项";
				tableHead[4] = "票数(百分比)";
				for(int i=0;i<poll_idStrs.length;i++){
					int poll_id = Integer.parseInt(poll_idStrs[i]);
					poll = new Poll();
					pb = new PollDAOImpl();
					pob = new PollOptionDAOImpl();
					poll.setName(pb.getNameByID(poll_id));
					poll.setAll_polls(pob.getAll_polls(poll_id));
					all = pob.getPOAll(poll_id);
					map1.put(i, poll);
					map2.put(i, all);
				}
				boolean flag = HVPMSTools.exportExcel(map1,map2, tableHead, response.getOutputStream());
				if(!flag){
					response.setContentType("text/html");
					response.getWriter().println("导出Excel失败。。。");
				}
			}else{
				response.setContentType("text/html");
				response.getWriter().println("系统出错，请联系开发者");
			}
		}else{
			response.setContentType("text/html");
			response.getWriter().println("谢绝跨路径访问");
		}
	}

}
